package com.apes.fn.ssm.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.ssm.model.CalculateProduct;
import com.apes.fn.ssm.model.CalculatedState;
import com.apes.fn.ssm.model.FittingMessage;
import com.apes.fn.ssm.repository.*;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.repository.ProductRepository;
import com.apes.scm.masterdata.stock.model.Location;
import com.apes.scm.masterdata.stock.repository.LocationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 类描述：
 *
 * @ClassName SelectionRangeService
 * @Description 配置测算范围
 * @Author wushilong
 * @Date 2022/7/8 16:59
 * @Version 1.0
 */
@Service("selectionRangeService")
public class SelectionRangeService extends DomainService {

    @Autowired
    private LocationRepository locationRepository;

    @Autowired
    private FittingMessageRepository fittingMessageRepository;

    @Autowired
    private BrandPriorityRepository brandPriorityRepository;

    @Autowired
    private StockConfigRepository stockConfigRepository;

    @Autowired
    private BrandPriorityDao brandPriorityDao;

    @Autowired
    private StockConfigDao stockConfigDao;

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private CalculateProductRepository calculateProductRepository;

    @Autowired
    private CalculatedStateRepository calculatedStateRepository;
    @Autowired
    private StoreMemberModelsImportRepository storeMemberModelsImportRepository;


    /**
     * 定制导入品牌优先级配置
     *
     */
    public Map importLocation (SimpleRequest request){
        //Excel信息
        JSONObject importData = request.get("importData");
        JSONArray field = (JSONArray) request.get("data");
        JSONObject exclObject = new JSONObject();                  //返回值

        JSONArray exclArr = new JSONArray();            //行内容
        JSONArray headerName = new JSONArray();         //头部
        JSONArray fieldName = new JSONArray();          //field
        for (Object o : field) {
            JSONObject webTab = (JSONObject) o;
            headerName.add(webTab.get("name"));
            fieldName.add(webTab.get("field"));
        }

        //用于过滤重复数据
        Set<String> locationSet = new HashSet<>();

        //业务逻辑
        importData.forEach((k, v) -> {

            //获得value ===Excel内容
            JSONArray excl = (JSONArray) v;
            JSONArray header = (JSONArray) excl.get(0); //首行数据
            String locationId;
            for (int i = 0; i < excl.size(); i++) {  //遍历每一行

                if (i == 0) { //跳过首行
                    continue;
                }

                JSONArray lineLong = (JSONArray) excl.get(i); //当前行
                if (lineLong.size() == 0) {
                    continue; //跳过空白行
                }
                //合并2个list为一个map,KEY为首行数据，Value为当前行数据
                Map<String, String> rst = IntStream.range(0, header.size()).collect(HashMap<String, String>::new,
                        (m, key) -> m.put(header.getString(key).replace(";", ""),
                                key >= lineLong.size() ? "" : (lineLong.getString(key) == null ? null : lineLong.getString(key).trim().replaceAll("[\\s]{2,}", " "))),
                        (m1, m2) -> {
                        });
                this.judgeTitle(rst);
                locationId = rst.get("库区编码");
                Location  location = locationRepository.findOne(locationId);

                //禁止导入重复数据
                if (!locationSet.add(location.getId())) throw new RuntimeException("导入重复数据，请重新导入！");

                exclArr.add(location);
            }
            exclObject.put(k, exclArr);
        });


        return MapUtil.mapper("items",exclArr,"msg","");
    }

    /**
     * 判断列头是否有异常
     * @param rst
     */
    private void judgeTitle(Map rst) {
        if (StringUtils.isEmpty(rst.get("库区名称")) || StringUtils.isEmpty(rst.get("库区编码")) ||
                StringUtils.isEmpty(rst.get("库区属性")) || StringUtils.isEmpty(rst.get("有效"))) {
            throw new RuntimeException("请重新导出文件导入，请按照导出文件导入！");
        }
    }

    /**
     *检测选择仓库是否配置品牌优先级和备货配置
     * @param request
     * @return
     */
    public Map allItems(SimpleRequest request){
        //判断是否已经有人开始测算了
        calculatedStateRepository.exec("begin P_DEL_PRODUAL_SQL(); end;");
        List<CalculatedState> primaryCalculatedStates = calculatedStateRepository.findAll();
        if (primaryCalculatedStates.size() > 0) {
            CalculatedState primaryCalculatedState = primaryCalculatedStates.get(0);
            if (primaryCalculatedState.isStepTwoMark()) throw new RuntimeException("当前已有存在的安全库存测算，请稍后再试！");
        }

        //获取前端传递数据
        JSONArray locationArray = request.getJO().getJSONArray("location");
        if (locationArray.size() <= 0 || Objects.isNull(locationArray)) throw new RuntimeException("请选择仓库！");
        List<FittingMessage> fittingMessages = request.getA("fittingMessageItems", FittingMessage.class);

        AtomicReference<Integer> brandPriorityCount = new AtomicReference<>(0);
        AtomicReference<Integer> stockConfigCount = new AtomicReference<>(0);
        AtomicReference<Integer> collect = new AtomicReference<>(0);//商品数


        //匹配选择的测算仓库是否配置了品牌优先级配置和备货配置
        locationArray.parallelStream().forEach(location -> {
            JSONObject locationJSON = (JSONObject) location;

            List<String> fittingMessageIdList = brandPriorityRepository.findAllFittingMessage(locationJSON.getString("id"));
            List<String> configFittingMessageIdList = stockConfigRepository.findAllFittingMessage(locationJSON.getString("id"));
            List<String> distinctFittingMessageId = fittingMessageIdList.stream().distinct().collect(Collectors.toList());
            int valid = 0;
            //根据当前仓库配置好的组合配件对比页面选择的组合配件
            for (FittingMessage fm :fittingMessages) {
                if (!fm.isValid()) continue;
                valid++;
                //对比备货配置
                if (!configFittingMessageIdList.contains(fm.getId())) stockConfigCount.getAndSet(stockConfigCount.get() + 1);
                //对比品牌优先级
                if (!distinctFittingMessageId.contains(fm.getId())) {
                    brandPriorityCount.getAndSet(brandPriorityCount.get() + 1);
                    continue;
                }
                //测算商品数量
                if (Objects.nonNull(fm.getBrand()) && fm.getBrand().size() > 0){
                    List<Map> brandCount = brandPriorityDao.findBrandCount(fm);
                    collect.updateAndGet(v -> v + Integer.parseInt(brandCount.get(0).get("COUNT").toString()));
                    this.sendSaveCalcuProData(fm, locationJSON.getString("id"));
                }else {
                    List<String> allByBrand = brandPriorityRepository.findAllByBrand(fm.getId(),locationJSON.getString("id"));
                    List<Map> brandCount = brandPriorityDao.findBrandCount(fm, allByBrand);
                    collect.updateAndGet(v -> v + Integer.parseInt(brandCount.get(0).get("COUNT").toString()));
                    this.sendSaveCalcuProData(fm, locationJSON.getString("id"));
                }
            }
            if (valid == 0 ) throw new RuntimeException("请选择组合配件！");
        });
        if (collect.get() == 0) throw new RuntimeException("未匹配到商品信息，请检查是否配置品牌优先级！");

        // 会员信息导入仓库判断
        List pageChoiceLocat = locationArray.stream().map(singleLoca -> {return ((JSONObject) singleLoca).getString("id");}).collect(Collectors.toList());
        List vipLocation = storeMemberModelsImportRepository.findAll(" SELECT DISTINCT LOCATION_ID FROM STOCK_STORE_MEMBER_MODELS_I A WHERE 1 = 1 ");
        pageChoiceLocat.addAll(vipLocation);
        pageChoiceLocat.removeAll(vipLocation);

        //封装数据返回
        return MapUtil.mapper("brandPriorityCount", brandPriorityCount.get(),"stockConfigCount", stockConfigCount.get(),"collect", collect.get(),
                "importNonConformanceLocatiCount", pageChoiceLocat.size());
    }

    /**
     * 安全库存测算备货配置明细（右边弹窗）
     * @param request
     * @return
     */
    public Map findStockConfigItems(SimpleRequest request){
        JSONArray locationItems = request.getJO().getJSONObject("conditionModel").getJSONArray("locationItems");
        if (locationItems.size() <= 0) throw new RuntimeException("请选择仓库！");
        JSONArray fittingMessageItems = request.getJO().getJSONObject("conditionModel").getJSONArray("fittingMessageItems");
        JSONArray validFittingMessage = new JSONArray();

        for (int i = 0; i < fittingMessageItems.size(); i++) {//去除未选择的组合配置
            JSONObject json = fittingMessageItems.getJSONObject(i);
            if (Boolean.parseBoolean(json.getString("valid"))) {
                validFittingMessage.add(json);
            }
        }
        if (validFittingMessage.size() <= 0) throw new RuntimeException("请选择组合配件！");

        List<Map> stockConfigList = stockConfigDao.findByLocationId(locationItems, validFittingMessage);//已配置备货配置明细

        List<String> locationId = stockConfigList.stream().map(stockConfig -> {
            return stockConfig.get("LOCATION_ID").toString();
        }).distinct().collect(Collectors.toList());//根据仓库id去重

        List<Map> onStockConfig = locationMatchingAccessories(locationItems, validFittingMessage, locationId);//未配置备货配置的仓库和组合配件名称


        return MapUtil.mapper("onStockConfig",onStockConfig,"stockConfigList",stockConfigList);

    }

    /**
     * 组装未配置组合配件的仓库
     * @param locationArray 仓库列表
     * @param fittingMessageArray 组合配件列表
     * @return
     */
    private List<Map> locationMatchingAccessories(JSONArray locationArray, JSONArray fittingMessageArray, List<String> locationId){
        List<Map> stockConfigList = new ArrayList<>();

        for (int i = 0; i < locationArray.size(); i++) {
            JSONObject locationJSON = locationArray.getJSONObject(i);
            List fittingMessageId = new ArrayList();
            if (locationId.contains(locationJSON.getString("id"))) {//判断当前仓库是否配置备货配置
                fittingMessageId = stockConfigRepository.findAllFittingMessage(locationJSON.getString("id"));
            }
            for (int j = 0; j < fittingMessageArray.size(); j++) {
                JSONObject fittingMessageJSON = fittingMessageArray.getJSONObject(j);
                if (fittingMessageId.contains(fittingMessageJSON.getString("id"))) continue;//判断
                stockConfigList.add(MapUtil.mapper("locationName",locationJSON.getString("name"),
                        "locationId",locationJSON.getString("id"),
                        "fittingMessageName",fittingMessageJSON.getString("name"),
                        "fittingMessageId",fittingMessageJSON.getString("id")));
            }
        }
        return stockConfigList;
    }


    /**
     * 安全库存测算品牌优先级明细（右边弹窗）
     * @param request
     * @return
     */
    public Map findBrandPriorityItems(SimpleRequest request){
        JSONArray locationItems = request.getJO().getJSONObject("conditionModel").getJSONArray("locationItems");
        if (locationItems.size() <= 0) throw new RuntimeException("请选择仓库！");
        JSONArray fittingMessageItems = request.getJO().getJSONObject("conditionModel").getJSONArray("fittingMessageItems");
        JSONArray validFittingMessages = new JSONArray();

        for (int i = 0; i < fittingMessageItems.size(); i++) {//去除未选择的组合配置
            JSONObject json = fittingMessageItems.getJSONObject(i);
            if (Boolean.parseBoolean(json.getString("valid"))) {
                validFittingMessages.add(json);
            }
        }
        if (validFittingMessages.size() <= 0) throw new RuntimeException("请选择组合配件！");

        Map<String, List<Map>> groupMap = getGroupMap(locationItems, validFittingMessages);    //根据仓库和组合配件名称查询全部品牌

        return brandMatchingAccessories(locationItems, validFittingMessages, groupMap);
    }

    /**
     * 根据仓库以及组合配件名称分组
     * @param locationItems
     * @param validFittingMessage
     * @return  Map<String, List<Map>>
     */
    private Map<String, List<Map>> getGroupMap(JSONArray locationItems, JSONArray validFittingMessage){
        List<Map> brandPriorities = brandPriorityDao.findByLocationId(locationItems, validFittingMessage);
        return  brandPriorities.stream().collect(Collectors.groupingBy( map -> {
            String locationId = map.get("LOCATION_ID").toString();
            String fittingNameId = map.get("FITTING_NAME_ID").toString();
            return locationId+","+fittingNameId;
        }));
    }

    /**
     * 组装未配置品牌优先级的仓库
     * @param locationArray 仓库列表
     * @param fittingMessageArray 组合配件列表
     * @return
     */
    private Map brandMatchingAccessories(JSONArray locationArray, JSONArray fittingMessageArray, Map<String, List<Map>> groupMap){
        List<Map> onBrandPriorityList = new ArrayList<>();
        List<Map> brandPriorityList = new ArrayList<>();

        locationArray.forEach( item -> {
             JSONObject location = (JSONObject) item;
            String locationId = location.getString("id");

            fittingMessageArray.forEach(FM -> {
                JSONObject fittingMessage = (JSONObject) FM;
                String fittingMessageId = fittingMessage.getString("id");

                String key = locationId+","+fittingMessageId;
                JSONArray brandArray = fittingMessage.getJSONArray("brand");
                //判断当前组合配件是否选择品牌
                if(Objects.nonNull(brandArray) && brandArray.size() > 0){
                    //判断是否配置组合配件
                    if (Objects.nonNull(groupMap.get(key))){
                        List<Map> brandGroup = groupMap.get(key);
                        List<String> brandIdList = brandGroup.stream()
                                .map( brandItem -> brandItem.get("BRAND_ID").toString())
                                .collect(Collectors.toList());  //将该组合配件已配置的品牌id汇总

                        //对比页面选择品牌和已配置品牌优先级的品牌
                        brandArray.forEach(brandItem ->{
                            JSONObject brand = (JSONObject) brandItem;
                            //是否配置品牌
                            if (brandIdList.contains(brand.getString("id"))){
                                brandGroup.forEach(brandPriority -> {
                                    if (brandPriority.get("BRAND_ID").toString().equals(brand.getString("id"))){
                                        brandPriorityList.add(brandPriority);
                                    }
                                });
                                return;
                            }
                            onBrandPriorityList.add(MapUtil.mapper("locationName",location.getString("name"),
                                    "locationId",location.getString("id"),
                                    "fittingMessageName",fittingMessage.getString("name"),
                                    "fittingMessageId",fittingMessage.getString("id"),
                                    "brandName",brand.getString("name"),
                                    "brandId",brand.getString("id")));
                        });
                    }else {//没有配置组合配件
                        brandArray.forEach(brandItem ->{
                            JSONObject brand = (JSONObject) brandItem;
                            onBrandPriorityList.add(MapUtil.mapper("locationName",location.getString("name"),
                                    "locationId",location.getString("id"),
                                    "fittingMessageName",fittingMessage.getString("name"),
                                    "fittingMessageId",fittingMessage.getString("id"),
                                    "brandName",brand.getString("name"),
                                    "brandId",brand.getString("id")));
                        });
                    }

                }else {//没有选择品牌
                    if (Objects.nonNull(groupMap.get(key))){//是否配置
                        brandPriorityList.addAll(groupMap.get(key));
                    }else{
                        onBrandPriorityList.add(MapUtil.mapper("locationName",location.getString("name"),
                                "locationId",location.getString("id"),
                                "fittingMessageName",fittingMessage.getString("name"),
                                "fittingMessageId",fittingMessage.getString("id")));
                    }
                }
            });
        });

        return MapUtil.mapper("onBrandPriorityList",onBrandPriorityList,"brandPriorityList",brandPriorityList);
    }

    /**
     * 安全库存测算商品列表明细（右边弹窗）
     * @param request
     * @return
     */
    public int saveCalculateProductAll(SimpleRequest request){
        //检查数据
        JSONObject getJO = request.getJO();
        JSONArray locationItems = getJO.getJSONArray("locationItems");
        if (locationItems.size() <= 0) throw new RuntimeException("请选择仓库！");
        JSONArray fittingMessageItems = getJO.getJSONArray("fittingMessageItems");

        List<String> validFittingMessagesID = new ArrayList<>();//提取id方便查询
        JSONArray validFittingMessages = new JSONArray();//选择了的组合配件

        for (int i = 0; i < fittingMessageItems.size(); i++) {//去除未选择的组合配置
            JSONObject json = fittingMessageItems.getJSONObject(i);
            if (Boolean.parseBoolean(json.getString("valid"))) {
                validFittingMessagesID.add(json.getString("id"));
                validFittingMessages.add(json);
            }
        }
        if (validFittingMessages.size() <= 0) throw new RuntimeException("请选择组合配件！");

        List<CalculateProduct> finalProduct = filterProduct(locationItems, validFittingMessages, new ArrayList<>());//最终商品数据

        calculateProductRepository.saveAll(finalProduct);

        return 1;
    }

    /**
     * 根据品牌过滤商品
     * @param locationItems
     * @param validFittingMessages
     * @return
     */
    private  List<CalculateProduct> filterProduct(JSONArray locationItems, JSONArray validFittingMessages,List<Map> filterProductQueue){
        //用来存放过滤后的结果
        Queue<CalculateProduct> finalProduct = new ConcurrentLinkedQueue<>();

        //根据已选择仓库查询商品详细信息
        locationItems.forEach( locationItem -> {
            JSONObject location = (JSONObject) locationItem;
            List<String> fittingMessageIdList = brandPriorityRepository.findAllFittingMessage(location.getString("id"));
            if (fittingMessageIdList.size() <= 0) return;
            //第一步： 根据配件分组商品信息
            Map<String, List<Map<String, String>>> categoryIdGroup = getCategoryGroup(fittingMessageIdList);

            //根据已选择的组合配件分层
            validFittingMessages.parallelStream().forEach(fmItem -> {
                JSONObject fittingMessages = (JSONObject) fmItem;
                //配件级别容器
                List<CalculateProduct> collectCategory = new ArrayList<>();

                List<String> CategoryId = fittingMessageRepository.findAllCategoryId(fittingMessages.getString("id"));
                // 是否选择测算品牌
                if (Objects.nonNull(fittingMessages.getJSONArray("brand")) && fittingMessages.getJSONArray("brand").size() > 0){
                    withBrand(location, categoryIdGroup, fittingMessages, collectCategory, CategoryId, filterProductQueue);
                }else {
                    withoutBrand(location, categoryIdGroup, fittingMessages, collectCategory, CategoryId, filterProductQueue);
                }
                // 商品状态
                JSONArray productStateArray = fittingMessages.getJSONArray("product");
                if (Objects.nonNull(productStateArray)){
                    //过滤商品状态
                    List states = productStateArray.stream().map(state -> ((JSONObject)state).getString("id")).collect(Collectors.toList());
                    finalProduct.addAll(collectCategory.stream().filter( cc -> states.contains(cc.getProduct().getState())).collect(Collectors.toList()));

//                    finalProduct.addAll(collectCategory.stream().filter( cc -> cc.getProduct().getState().equals(state.getString("id"))).collect(Collectors.toList()));
                    return;
                }
                finalProduct.addAll(collectCategory);
            });
        });
        return new ArrayList<>(finalProduct);
    }

    /**
     * 根据配件分组商品
     * @param fittingMessageIdList
     * @return
     */
    private Map<String, List<Map<String, String>>> getCategoryGroup(List<String> fittingMessageIdList) {
        List<String> distinctFittingMessageId = fittingMessageIdList.stream().distinct().collect(Collectors.toList());
        //获取该配件所以商品信息
        List<String> allCategoryId = fittingMessageRepository.findAllCategoryId(distinctFittingMessageId);
        List<Map<String, String>> products = new ArrayList<>();
        for (String categoryId: allCategoryId) {
             products.addAll(productRepository.findAllByCategory(categoryId));
        }


        //根据配件分组
        return products.stream().collect(Collectors.groupingBy(product -> product.get("CATEGORY_ID")));
    }

    /**
     * 视图页面选择品牌，过滤视图页面未选择的品牌
     * @param location
     * @param categoryIdGroup
     * @param fittingMessages
     * @param collectCategory
     * @param CategoryId
     */
    private void withBrand(JSONObject location, Map<String, List<Map<String, String>>> categoryIdGroup,
                           JSONObject fittingMessages, List<CalculateProduct> collectCategory, List<String> CategoryId,List filterProductQueue) {
        CategoryId.forEach(categoryItem -> {
            //获取配件分组
            List<Map<String,String>> categoryTeam = categoryIdGroup.get(categoryItem);
            if (Objects.isNull(categoryTeam)) return;

            //遍历品牌
            fittingMessages.getJSONArray("brand").forEach(brandItem -> {
                //品牌级别容器
                JSONObject brand = (JSONObject) brandItem;
                //过滤没有选择的品牌
                List<Map<String,String>> collectBrand = categoryTeam.stream().filter(ct -> ct.get("BRAND_ID").equals(brand.getString("id"))).collect(Collectors.toList());
                //当前仓库，当前品牌优先级
                Map<String, String> brandPriority = brandPriorityRepository.queryByCondition(location.getString("id"),
                        fittingMessages.getString("id"), brand.getString("id"));
                //拼装数据
                collectCategory.addAll(jointCalculateProductAll(collectBrand,brandPriority,filterProductQueue));
            });
        });
    }

    /**
     * 视图页面未选择品牌，过滤品牌优先级未配置的商品信息
     * @param location
     * @param categoryIdGroup
     * @param fittingMessages
     * @param collectCategory
     * @param CategoryId
     */
    private void withoutBrand(JSONObject location, Map<String, List<Map<String, String>>> categoryIdGroup, JSONObject fittingMessages,
                              List<CalculateProduct> collectCategory, List<String> CategoryId, List filterProductQueue) {
        CategoryId.forEach(categoryItem ->{
            //获取配件分组
            List<Map<String, String>> categoryTeam = categoryIdGroup.get(categoryItem);
            if (Objects.isNull(categoryTeam)) return;
            //获取已配置的品牌
            List<String> thenBrandId = brandPriorityRepository.findAllByBrand(fittingMessages.getString("id"), location.getString("id"));
            //遍历品牌
            thenBrandId.forEach( brandId -> {
                // 品牌级别容器 过滤掉没有配置的品牌
                List<Map<String, String>> collectBrand = categoryTeam.stream().filter(ct -> ct.get("BRAND_ID").equals(brandId)).collect(Collectors.toList());
                //当前仓库，当前品牌优先级
                Map<String, String> brandPriority = brandPriorityRepository.queryByCondition(location.getString("id"), fittingMessages.getString("id"), brandId);
                //拼装数据，并发送事务发件箱
                collectCategory.addAll(jointCalculateProductAll(collectBrand,brandPriority,filterProductQueue));
            });
        });
    }

    /**
     * 拼接测算商品明细
     * @param finalProduct
     */
    private List<CalculateProduct> jointCalculateProductAll(List<Map<String,String>> finalProduct, Map<String, String> brandPriority, List filterProductQueue){
        List<CalculateProduct> calculateProducts = new ArrayList<>();
        if (finalProduct.size() <= 0) return new ArrayList<>(calculateProducts);
        finalProduct.forEach(product -> {
            //设置测算商品明细
            CalculateProduct calculateProduct = new CalculateProduct();
            calculateProduct.setLocation(brandPriority.get("LOCATION_ID"));

            Product newProduct = new Product();
            newProduct.setId(product.get("ID"));
            newProduct.setState(product.get("STATE"));
            calculateProduct.setProduct(newProduct);

            calculateProduct.setBrandPriority(brandPriority.get("PRIORITY"));
            calculateProduct.setBrand(product.get("BRAND_ID"));
            calculateProduct.setCategory(product.get("CATEGORY_ID"));
            calculateProduct.setOemId(product.get("OEM_ID"));
            calculateProduct.setFittingMessage(new FittingMessage(brandPriority.get("FITTING_NAME")));
            calculateProducts.add(calculateProduct);
            //设置展示商品明细
            String state = "";
            switch (product.get("STATE")) {
                case "0":
                    state = "正常";
                    break;
                case "2":
                    state = "停产下市";
                    break;
                case "3":
                    state = "停用";
                    break;
                case "5":
                    state = "预上市";
                    break;
            }
            filterProductQueue.add(MapUtil.mapper("productId",product.get("ID"),
                    "productName", product.get("NAME"),
                    "categoryName",product.get("CATEGORY_NAME"),
                    "brand",product.get("BRAND_NAME"),
                    "state",state));
        });
        return calculateProducts;
    }

    /**
     * 导入会员信息 - 右弹出框
     * @return
     */
    public Map vipLievenPopup(SimpleRequest request) {
        List<Map> importVipSum = storeMemberModelsImportRepository.importVipSum();
        List choiceLocati = request.getJO().getJSONObject("conditionModel").getJSONArray("locationItems")
                .stream().map(locationId -> {return ((JSONObject)locationId).getString("id");})
                .collect(Collectors.toList());

        List importVipLoca = storeMemberModelsImportRepository.findAll(" SELECT DISTINCT LOCATION_ID FROM STOCK_STORE_MEMBER_MODELS_I A WHERE 1 = 1 ");
        choiceLocati.removeAll(importVipLoca);

        List queryLocaCondi = Arrays.asList(MapUtil.mapper("field", "id", "value", choiceLocati, "operator", "in"));
        List nonVipLieveInfo = locationRepository.findAll(JpaDsl.toCriteria(queryLocaCondi));
        return MapUtil.mapper("nonVipLieveInfo", nonVipLieveInfo, "vipLievenInfo", importVipSum);
    }

    /**
     * 测算商品明细
     * @return
     */
    public Map categoryPopup(SimpleRequest request){
        JSONArray locationItems = request.getJO().getJSONObject("conditionModel").getJSONArray("locationItems");
        if (locationItems.size() <= 0) throw new RuntimeException("请选择仓库！");
        JSONArray fittingMessageItems = request.getJO().getJSONObject("conditionModel").getJSONArray("fittingMessageItems");
        if (fittingMessageItems.size() <= 0) throw new RuntimeException("请选择组合配件！");

        List<String> validFittingMessagesID = new ArrayList<>();//提取id方便查询
        JSONArray validFittingMessages = new JSONArray();//选择了的组合配件

        for (int i = 0; i < fittingMessageItems.size(); i++) {//去除未选择的组合配置
            JSONObject json = fittingMessageItems.getJSONObject(i);
            if (Boolean.valueOf(json.getString("valid"))) {
                validFittingMessagesID.add(json.getString("id"));
                validFittingMessages.add(json);
            }
        }

        //最终商品数据容器
        List filterProductQueue = Collections.synchronizedList(new ArrayList());;
        //查询商品详细信息并写入容器里面
        filterProduct(locationItems, validFittingMessages, filterProductQueue);

        return MapUtil.mapper("category",new ArrayList<>(filterProductQueue));
    }

    /**
     * 保存参与测算的仓库和组合配件
     * @param request
     */
    public int saveCalculatedState(SimpleRequest request){
        List<CalculatedState> primaryCalculatedStates = calculatedStateRepository.findAll();
        if (primaryCalculatedStates.size() > 0) {
            CalculatedState primaryCalculatedState = primaryCalculatedStates.get(0);
            if (primaryCalculatedState.isStepTwoMark()) return 1;
        }

        //删除上一次数据
        calculatedStateRepository.deleteAll();

        //检查数据
        JSONArray locationItems = request.getJO().getJSONObject("conditionModel").getJSONArray("locationItems");
        if (locationItems.size() <= 0 || Objects.isNull(locationItems)) throw new RuntimeException("请选择仓库！");
        JSONArray fittingMessageItems = request.getJO().getJSONObject("conditionModel").getJSONArray("fittingMessageItems");
        if (fittingMessageItems.size() <= 0 || Objects.isNull(fittingMessageItems)) throw new RuntimeException("请选择组合配件！");

        JSONArray validFittingMessages = new JSONArray();//选择了的组合配件

        for (int i = 0; i < fittingMessageItems.size(); i++) {//去除未选择的组合配置
            JSONObject json = fittingMessageItems.getJSONObject(i);
            if (Boolean.valueOf(json.getString("valid"))) {
                validFittingMessages.add(json);
            }
        }

        List<CalculatedState> calculatedStates = new ArrayList<>();
        //根据仓库分配组合配件
        for (int i = 0; i < locationItems.size(); i++) {
            JSONObject locationItem = locationItems.getJSONObject(i);
            List<String> fittingMessageIdList = brandPriorityRepository.findAllFittingMessage(locationItem.getString("id"));
            if (fittingMessageIdList.size() <= 0) continue;
            for (int j = 0; j < validFittingMessages.size(); j++) {
                JSONObject fittingMessagesItem = validFittingMessages.getJSONObject(j);
                if (!fittingMessageIdList.contains(fittingMessagesItem.getString("id"))) continue;
                Location location = new Location();
                location.setId(locationItem.getString("id"));
                location.setName(locationItem.getString("name"));

                FittingMessage fittingMessage = new FittingMessage();
                fittingMessage.setId(fittingMessagesItem.getString("id"));
                fittingMessage.setName(fittingMessagesItem.getString("name"));

                CalculatedState calculatedState = new CalculatedState();
                calculatedState.setLocation(location);
                calculatedState.setFittingMessage(fittingMessage);

                calculatedStates.add(calculatedState);
            }
        }

        calculatedStateRepository.saveAll(calculatedStates);
        return 1;
    }

    /**
     * 主要目的
     * 保存商品条件数据
     * */
    private void sendSaveCalcuProData(FittingMessage fittingMessage, String locationId) {
        Map condiValues = new HashMap();
        condiValues.put("LOCATION_ID", locationId);
        condiValues.put("FITTING_MESSAGE_ID", fittingMessage.getId());
        if (!ObjectUtils.isEmpty(fittingMessage.getBrand())) {
            String condiValue = brandPriorityDao.getQueryString(fittingMessage.getBrand());
            condiValues.put("BRAND_ID", condiValue);

        } else {
            List<String> allByBrand = brandPriorityRepository.findAllByBrand(fittingMessage.getId(), locationId);
            condiValues.put("BRAND_ID", (allByBrand.toString()).substring(1, allByBrand.toString().length() - 1).replace(" ", ""));
        }

        if (Objects.nonNull(fittingMessage.getProduct()) && !"[]".equals(fittingMessage.getProduct())){
            String condiValue = brandPriorityDao.getQueryString(JSONArray.parseArray(fittingMessage.getProduct()));
            condiValues.put("STATE", condiValue);

        }
        SpringManager.getBean(CalculateProductService.class).saveCalcuCondiData(condiValues);

    }
}
